package com.zhudoo.zhilian.util;

import java.util.*;

/**
 * wangnian创建于 2016 11 24
 */
public class MapConverter {

    /**
     * ：
     * requestmap转map的方法
     *
     * @param requestParams
     * @return
     */
    public static HashMap requestParameterMapToHashMap(Map requestParams) {
        HashMap resultMap = new HashMap(10);
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            resultMap.put(name, valueStr);
        }
        return resultMap;
    }

    /**
     * Map转换成url参数
     *
     * @param map
     * @param isSort    是否排序
     * @param removeKey 不包含的key元素集
     * @return
     */
    public static String getOrderedQueryStr(Map<String, Object> map, boolean isSort, Set<String> removeKey) {
        StringBuffer param = new StringBuffer();
        List<String> msgList = new ArrayList<String>();
        for (Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {
            String key = it.next();
            Object value = map.get(key);
            if (removeKey != null && removeKey.contains(key)) {
                continue;
            }
            msgList.add(key + "=" + value);
        }
        if (isSort) {
            // 排序
            Collections.sort(msgList);
        }
        for (int i = 0; i < msgList.size(); i++) {
            String msg = msgList.get(i);
            if (i > 0) {
                param.append("&");
            }
            param.append(msg);
        }
        return param.toString();
    }

}

